<template>
    <div class="work-calendar-container">
      <!-- 标签页区域 -->
      <div class="tabs-container">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="分类" name="category"></el-tab-pane>
          <el-tab-pane label="班组" name="group"></el-tab-pane>
        </el-tabs>
      </div>
  
      <div class="calendar-main">
        <!-- 左侧分类/班组列表 -->
        <div class="left-sidebar">
          <div class="filter-header">
            <h3>{{ activeTab === 'category' ? '分类' : activeTab === 'group' ? '班组' : '人员' }}</h3>
          </div>
          <div class="filter-content">
            <template v-if="activeTab === 'category'">
              <div class="filter-item" :class="{ active: selectedCategoryId === null }" @click="selectCategory(null)">
                全部
              </div>
              <div class="filter-item" :class="{ active: selectedCategoryId === 1 }" @click="selectCategory(1)">
                注塑工
              </div>
              <div class="filter-item" :class="{ active: selectedCategoryId === 2 }" @click="selectCategory(2)">
                机加工
              </div>
              <div class="filter-item" :class="{ active: selectedCategoryId === 3 }" @click="selectCategory(3)">
                组装
              </div>
              <div class="filter-item" :class="{ active: selectedCategoryId === 4 }" @click="selectCategory(4)">
                仓库
              </div>
            </template>
            <template v-else-if="activeTab === 'group'">
              <div class="filter-item" :class="{ active: selectedGroupId === null }" @click="selectGroup(null)">
                全部
              </div>
              <template v-for="groupType in filteredGroupTypes" :key="groupType.id">
                <div class="group-category">{{ groupType.name }}</div>
                <div 
                  v-for="group in getGroupsByType(groupType.id)" 
                  :key="group.groupId" 
                  class="filter-item sub-item" 
                  :class="{ active: selectedGroupId === group.groupId }" 
                  @click="selectGroup(group.groupId)"
                >
                  {{ group.groupName }}
                </div>
              </template>
            </template>
          </div>
        </div>
  
        <!-- 右侧日历 -->
        <div class="right-content">
          <div class="calendar-header">
            <div class="date-selector">
              <el-date-picker
                v-model="selectedDate"
                type="month"
                format="YYYY年MM月"
                placeholder="选择月份"
                @change="handleDateChange"
              />
            </div>
            <div class="calendar-actions">
              <el-button-group>
                <el-button size="small" @click="goToPrevMonth">上个月</el-button>
                <el-button size="small" @click="goToToday">当前月</el-button>
                <el-button size="small" @click="goToNextMonth">下个月</el-button>
              </el-button-group>
            </div>
          </div>
  
          <div class="calendar-body">
            <div class="calendar-header-row">
              <div class="calendar-cell header-cell" v-for="day in weekDays" :key="day">{{ day }}</div>
            </div>
            <div class="calendar-week" v-for="(week, weekIndex) in calendarWeeks" :key="weekIndex">
              <div 
                v-for="(day, dayIndex) in week" 
                :key="dayIndex" 
                class="calendar-cell"
                :class="{
                  'other-month': day.isOtherMonth,
                  'today': day.isToday,
                  'holiday': day.isHoliday,
                  'workday': !day.isHoliday && day.isWorkDay
                }"
              >
                <div class="date-cell">
                  <div class="date-number">{{ day.day }}</div>
                  <div class="date-info">
                    <span v-if="day.lunarDate" class="lunar-date">{{ day.lunarDate }}</span>
                    <span v-if="day.holidayName" class="holiday-name" :class="{ [`holiday-type-${day.holidayType}`]: true }">
                      {{ day.holidayName }}
                    </span>
                  </div>
                </div>
                <div class="group-status">
                  <template v-if="!day.isOtherMonth">
                    <div v-for="group in getFilteredGroups(day.groups)" :key="group.groupId" class="group-item" :class="{ [`status-${group.status}`]: true }">
                      <el-tooltip :content="group.groupName + (group.remark ? '：' + group.remark : '')" placement="top">
                        <div class="group-tag">
                          <span class="group-name">{{ group.groupName }}</span>
                          <div class="group-actions">
                            <el-button 
                              v-if="group.status === 0" 
                              type="primary" 
                              size="mini" 
                              @click.stop.prevent="handleSubmitDraft(group)"
                              class="action-btn"
                            >提交</el-button>
                            <el-button 
                              v-if="group.status === 1" 
                              type="success" 
                              size="mini" 
                              @click.stop.prevent="handleDeploy(group)"
                              class="action-btn"
                            >上架</el-button>
                            <el-button 
                              v-if="group.status === 2" 
                              type="info" 
                              size="mini" 
                              disabled
                              class="action-btn"
                            >已上架</el-button>
                          </div>
                        </div>
                      </el-tooltip>
                    </div>
                  </template>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, computed, onMounted, watch } from 'vue';
  import http from '@/api/http';
  import { ElMessage } from 'element-plus';
  
  // 活跃标签页
  const activeTab = ref('category');
  
  // 日期相关
  const currentDate = new Date();
  const selectedDate = ref(currentDate);
  const selectedYear = ref(currentDate.getFullYear());
  const selectedMonth = ref(currentDate.getMonth() + 1);
  
  // 筛选相关
  const selectedCategoryId = ref(null);
  const selectedGroupId = ref(null);
  
  // 日历数据
  const calendarData = ref([]);
  
  // 分组数据
  const allGroups = ref([]);
  const groupTypes = [
    { id: 1, name: '注塑工' },
    { id: 2, name: '机加工' },
    { id: 3, name: '组装' },
    { id: 4, name: '仓库' }
  ];
  
  // 星期列表
  const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
  
  // 计算出过滤后的分组类型
  const filteredGroupTypes = computed(() => {
    if (selectedCategoryId.value === null) {
      return groupTypes;
    } else {
      return groupTypes.filter(type => type.id === selectedCategoryId.value);
    }
  });
  
  // 根据类型获取分组
  const getGroupsByType = (typeId) => {
    return allGroups.value.filter(group => group.groupType === typeId);
  };
  
  // 获取过滤后的分组
  const getFilteredGroups = (groups) => {
    if (!groups) return [];
    
    if (selectedCategoryId.value === null && selectedGroupId.value === null) {
      return groups;
    } else if (selectedCategoryId.value !== null && selectedGroupId.value === null) {
      return groups.filter(group => group.groupType === selectedCategoryId.value);
    } else if (selectedGroupId.value !== null) {
      return groups.filter(group => group.groupId === selectedGroupId.value);
    }
    
    return groups;
  };
  
  // 计算日历周数据
  const calendarWeeks = computed(() => {
    const weeks = [];
    let currentWeek = [];
    
    // 获取当月第一天
    const firstDay = new Date(selectedYear.value, selectedMonth.value - 1, 1);
    const firstDayOfWeek = firstDay.getDay();
    
    // 获取上月的最后几天
    const prevMonthLastDate = new Date(selectedYear.value, selectedMonth.value - 1, 0).getDate();
    for (let i = firstDayOfWeek - 1; i >= 0; i--) {
      const prevMonthDay = prevMonthLastDate - i;
      const prevDate = new Date(selectedYear.value, selectedMonth.value - 2, prevMonthDay);
      
      currentWeek.push({
        date: prevDate.toISOString().split('T')[0] + ' 00:00:00',
        dayOfWeek: prevDate.getDay() + 1,
        day: prevMonthDay,
        lunarDate: '',
        isHoliday: false,
        holidayName: '',
        holidayType: 0,
        isWorkDay: true,
        groups: [],
        isOtherMonth: true,
        isToday: isSameDay(prevDate, new Date())
      });
    }
    
    // 获取当月天数
    const lastDay = new Date(selectedYear.value, selectedMonth.value, 0);
    const daysInMonth = lastDay.getDate();
    
    // 填充当月日期
    for (let day = 1; day <= daysInMonth; day++) {
      const date = new Date(selectedYear.value, selectedMonth.value - 1, day);
      const dayOfWeek = date.getDay() + 1; // 转为1-7表示周日到周六
      
      // 查找该日期在日历数据中的信息
      const dayData = calendarData.value.find(d => {
        const dDate = new Date(d.date);
        return dDate.getDate() === day;
      }) || {
        date: date.toISOString().split('T')[0] + ' 00:00:00',
        dayOfWeek,
        day,
        lunarDate: '',
        isHoliday: dayOfWeek === 7 || dayOfWeek === 1, // 默认周六日为假日
        holidayName: (dayOfWeek === 7 || dayOfWeek === 1) ? '周末' : '',
        holidayType: 2,
        isWorkDay: !(dayOfWeek === 7 || dayOfWeek === 1),
        groups: []
      };
      
      // 添加到当前周
      currentWeek.push({
        ...dayData,
        isOtherMonth: false,
        isToday: isSameDay(date, new Date())
      });
      
      // 一周结束或当月最后一天
      if (dayOfWeek === 7 || day === daysInMonth) {
        weeks.push([...currentWeek]);
        currentWeek = [];
      }
    }
    
    // 如果最后一周不满7天，添加下个月的前几天
    if (currentWeek.length > 0) {
      const daysNeeded = 7 - currentWeek.length;
      for (let i = 1; i <= daysNeeded; i++) {
        const nextDate = new Date(selectedYear.value, selectedMonth.value, i);
        
        currentWeek.push({
          date: nextDate.toISOString().split('T')[0] + ' 00:00:00',
          dayOfWeek: nextDate.getDay() + 1,
          day: i,
          lunarDate: '',
          isHoliday: false,
          holidayName: '',
          holidayType: 0,
          isWorkDay: true,
          groups: [],
          isOtherMonth: true,
          isToday: isSameDay(nextDate, new Date())
        });
      }
      weeks.push(currentWeek);
    }
    
    // 确保总是显示6行
    while (weeks.length < 6) {
      const lastWeek = weeks[weeks.length - 1];
      const lastDay = lastWeek[lastWeek.length - 1];
      const nextWeek = [];
      
      for (let i = 1; i <= 7; i++) {
        const day = parseInt(lastDay.day) + i;
        const nextDate = new Date(selectedYear.value, selectedMonth.value, day - lastDay.day);
        
        nextWeek.push({
          date: nextDate.toISOString().split('T')[0] + ' 00:00:00',
          dayOfWeek: ((lastDay.dayOfWeek - 1 + i) % 7) + 1,
          day: day - lastDay.day,
          lunarDate: '',
          isHoliday: false,
          holidayName: '',
          holidayType: 0,
          isWorkDay: true,
          groups: [],
          isOtherMonth: true,
          isToday: isSameDay(nextDate, new Date())
        });
      }
      
      weeks.push(nextWeek);
    }
    
    return weeks;
  });
  
  // 检查两个日期是否是同一天
  function isSameDay(date1, date2) {
    return date1.getFullYear() === date2.getFullYear() &&
           date1.getMonth() === date2.getMonth() &&
           date1.getDate() === date2.getDate();
  }
  
  // 选择分类
  const selectCategory = (categoryId) => {
    selectedCategoryId.value = categoryId;
    selectedGroupId.value = null;
  };
  
  // 选择班组
  const selectGroup = (groupId) => {
    selectedGroupId.value = groupId;
  };
  
  // 处理日期变化
  const handleDateChange = (date) => {
    if (date) {
      selectedYear.value = date.getFullYear();
      selectedMonth.value = date.getMonth() + 1;
      fetchCalendarData();
    }
  };
  
  // 跳转到上个月
  const goToPrevMonth = () => {
    if (selectedMonth.value === 1) {
      selectedYear.value--;
      selectedMonth.value = 12;
    } else {
      selectedMonth.value--;
    }
    selectedDate.value = new Date(selectedYear.value, selectedMonth.value - 1, 1);
    fetchCalendarData();
  };
  
  // 跳转到当前月
  const goToToday = () => {
    const today = new Date();
    selectedYear.value = today.getFullYear();
    selectedMonth.value = today.getMonth() + 1;
    selectedDate.value = today;
    fetchCalendarData();
  };
  
  // 跳转到下个月
  const goToNextMonth = () => {
    if (selectedMonth.value === 12) {
      selectedYear.value++;
      selectedMonth.value = 1;
    } else {
      selectedMonth.value++;
    }
    selectedDate.value = new Date(selectedYear.value, selectedMonth.value - 1, 1);
    fetchCalendarData();
  };
  
  // 获取日历数据
  const fetchCalendarData = async () => {
    try {
      const params = {
        queryYear: selectedYear.value,
        queryMonth: selectedMonth.value,
        queryGroupId: selectedGroupId.value || 0,
        queryGroupType: selectedCategoryId.value || "string"
      };
      
      const response = await http.post('/api/Workforce/GetWorkforceCalendar', params);
      
      if (response && response.status) {
        calendarData.value = response.data.calendarData || [];
        
        // 收集所有分组
        if (calendarData.value.length > 0) {
          const firstDay = calendarData.value[0];
          if (firstDay && firstDay.groups) {
            allGroups.value = firstDay.groups;
          }
        }
      } else {
        console.error('获取日历数据失败:', response?.message || '未知错误');
      }
    } catch (error) {
      console.error('获取日历数据出错:', error);
    }
  };
  
  // 监听标签页变化
  watch(activeTab, (newTab) => {
    // 切换标签页时，重置筛选条件
    if (newTab === 'category') {
      selectedCategoryId.value = null;
    } else if (newTab === 'group') {
      selectedGroupId.value = null;
    }
  });
  
  // 组件挂载时加载数据
  onMounted(() => {
    fetchCalendarData();
  });
  
  // 处理提交草稿
  const handleSubmitDraft = (group) => {
    console.log('提交草稿', group);
    // 调用API提交草稿
    http.post('/api/Workforce/SubmitDraft', { groupId: group.groupId })
      .then(response => {
        if (response && response.status) {
          // 提交成功后刷新日历数据
          fetchCalendarData();
          // 显示成功消息
          ElMessage.success('提交成功');
        } else {
          ElMessage.error(response?.message || '提交失败');
        }
      })
      .catch(error => {
        console.error('提交草稿出错:', error);
        ElMessage.error('提交失败');
      });
  };
  
  // 处理上架
  const handleDeploy = (group) => {
    console.log('执行上架', group);
    // 调用API执行上架
    http.post('/api/Workforce/Deploy', { groupId: group.groupId })
      .then(response => {
        if (response && response.status) {
          // 上架成功后刷新日历数据
          fetchCalendarData();
          // 显示成功消息
          ElMessage.success('上架成功');
        } else {
          ElMessage.error(response?.message || '上架失败');
        }
      })
      .catch(error => {
        console.error('上架出错:', error);
        ElMessage.error('上架失败');
      });
  };
  </script>
  
  <style lang="scss" scoped>
  .work-calendar-container {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: calc(100vh - 84px);
    
    .tabs-container {
      background-color: #fff;
      padding: 20px 20px 0;
      border-radius: 4px;
      margin-bottom: 20px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
    
    .calendar-main {
      display: flex;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      overflow: hidden;
      
      .left-sidebar {
        width: 180px;
        border-right: 1px solid #ebeef5;
        background-color: #f8f9fa;
        
        .filter-header {
          padding: 15px;
          border-bottom: 1px solid #ebeef5;
          
          h3 {
            margin: 0;
            font-size: 16px;
            font-weight: 500;
            color: #303133;
          }
        }
        
        .filter-content {
          padding: 10px 0;
          
          .filter-item {
            padding: 10px 15px;
            cursor: pointer;
            font-size: 14px;
            color: #606266;
            
            &:hover {
              background-color: #f0f2f5;
              color: #409eff;
            }
            
            &.active {
              background-color: #ecf5ff;
              color: #409eff;
              font-weight: 500;
            }
            
            &.sub-item {
              padding-left: 25px;
            }
          }
          
          .group-category {
            padding: 10px 15px;
            font-size: 13px;
            color: #909399;
            font-weight: 500;
            background-color: #f5f7fa;
            border-top: 1px solid #ebeef5;
            border-bottom: 1px solid #ebeef5;
            margin-top: 5px;
          }
        }
      }
      
      .right-content {
        flex: 1;
        padding: 20px;
        
        .calendar-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 20px;
          
          .date-selector {
            .el-date-editor {
              width: 180px;
            }
          }
        }
        
        .calendar-body {
          border: 1px solid #ebeef5;
          border-radius: 4px;
          
          .calendar-header-row {
            display: flex;
            background-color: #f5f7fa;
            border-bottom: 1px solid #ebeef5;
            
            .header-cell {
              flex: 1;
              height: 40px;
              display: flex;
              align-items: center;
              justify-content: center;
              font-weight: 500;
              color: #606266;
              
              &:first-child, &:last-child {
                color: #f56c6c;
              }
            }
          }
          
          .calendar-week {
            display: flex;
            min-height: 140px;
            height: auto;
            border-bottom: 1px solid #ebeef5;
            
            &:last-child {
              border-bottom: none;
            }
            
            .calendar-cell {
              flex: 1;
              border-right: 1px solid #ebeef5;
              padding: 8px;
              position: relative;
              display: flex;
              flex-direction: column;
              
              &:last-child {
                border-right: none;
              }
              
              &.other-month {
                background-color: #f9f9f9;
                
                .date-number {
                  color: #c0c4cc;
                }
                
                .date-info {
                  .lunar-date, .holiday-name {
                    color: #c0c4cc;
                  }
                }
              }
              
              &.today {
                background-color: #f0f9eb;
                
                .date-number {
                  color: #67c23a;
                  font-weight: bold;
                }
              }
              
              &.holiday {
                .date-number {
                  color: #f56c6c;
                }
                
                .holiday-name {
                  color: #f56c6c;
                }
              }
              
              .date-cell {
                text-align: center;
                margin-bottom: 8px;
                
                .date-number {
                  font-size: 16px;
                  font-weight: 500;
                  color: #303133;
                }
                
                .date-info {
                  font-size: 12px;
                  color: #909399;
                  margin-top: 3px;
                  display: flex;
                  flex-direction: column;
                  align-items: center;
                  
                  .lunar-date {
                    margin-bottom: 2px;
                  }
                  
                  .holiday-name {
                    padding: 0 4px;
                    background-color: #fef0f0;
                    border-radius: 2px;
                    
                    &.holiday-type-1 {
                      background-color: #f8f6ec;
                      color: #e6a23c;
                    }
                    
                    &.holiday-type-2 {
                      background-color: #fef0f0;
                      color: #f56c6c;
                    }
                    
                    &.holiday-type-3 {
                      background-color: #ecf5ff;
                      color: #409eff;
                    }
                  }
                }
              }
              
              .group-status {
                display: flex;
                flex-direction: column;
                gap: 5px;
                margin-top: 5px;
                flex-grow: 1;
                overflow-y: auto;
                max-height: 200px;
                
                .group-item {
                  margin-bottom: 5px;
                  
                  .group-tag {
                    font-size: 12px;
                    padding: 4px 6px;
                    border-radius: 4px;
                    color: #fff;
                    cursor: pointer;
                    box-sizing: border-box;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    min-height: 28px;
                    
                    .group-name {
                      white-space: nowrap;
                      overflow: hidden;
                      text-overflow: ellipsis;
                      flex: 1;
                    }
                    
                    .group-actions {
                      display: flex;
                      gap: 2px;
                      margin-left: 4px;
                      
                      .action-btn {
                        padding: 1px 3px;
                        font-size: 10px;
                        height: auto;
                        line-height: 1.2;
                        min-height: 20px;
                      }
                    }
                  }
                  
                  &.status-0 .group-tag {
                    background-color: #909399;
                  }
                  
                  &.status-1 .group-tag {
                    background-color: #67c23a;
                  }
                  
                  &.status-2 .group-tag {
                    background-color: #e6a23c;
                  }
                  
                  &.status-3 .group-tag {
                    background-color: #f56c6c;
                  }
                }
              }
            }
          }
        }
      }
    }
  }
  </style>